#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import json
import os
import shutil

import pandas as pd
from datetime import datetime, timezone
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from utils import get_non_recursive_folders


def get_time_second(time_str):
    dt = datetime.strptime(time_str, '%H:%M:%S')
    return dt


def get_time_day(time_str):
    dt = datetime.strptime(time_str, '%Y-%m-%d')
    # 将本地时间转换为 UTC 时间
    dt_utc = dt.astimezone(timezone.utc)
    # 将 datetime 对象转换为时间戳
    timestamp = int(dt_utc.timestamp())
    return timestamp


def main(json_path, save_path):

    result = {
        "true_result": [],
        "event_result": [],
        "yongdu_result": []
    }

    color_dict = {
        "单车": 1,
        "追尾": 2,
        "自燃": 3,
        "多车": 4
    }

    with open(json_path, 'r', encoding='utf-8') as f:
        data = json.load(f)

        if data["truthValue"] != []:
            for i in data["truthValue"]:
                level = 0
                for k in color_dict.keys():
                    if k in i["eventType"]:
                        level = color_dict[k]
                result["true_result"].append({"eventTime": datetime.strptime(i["eventTime"].split(' ')[1], '%H:%M'),
                                              "secLevel": level})
            for j in data["algorithmValue"]:
                if j["eventType"] == "阻断":
                    for m in j["interval"]:
                        result["event_result"].append({"eventTime": datetime.strptime(m["时间"].split(' ')[1], '%H:%M:%S'),
                                                       "secLevel": int(j["level"])})
                else:
                    for n in j["interval"]:
                        result["yongdu_result"].append({"eventTime": datetime.strptime(n["时间"].split(' ')[1], '%H:%M:%S'),
                                                        "secLevel": int(j["level"])})

    # 计算时间点位置
    start_time = datetime.strptime("00:00:00", "%H:%M:%S")
    end_time = datetime.strptime("23:59:59", "%H:%M:%S")

    # 将时间转换为相对于起始时间的分钟数，用于定位
    start_min = 0
    end_min = (end_time - start_time).total_seconds() / 60
    color_dict = {1: "cyan", 2: "yellow", 3: "orange", 4: "red", 5: "purple"}

    for day, org_info in result.items():

        fig, ax = plt.subplots(figsize=(15, 2))
        # 绘制全绿的条形图
        ax.add_patch(patches.Rectangle((start_min, 0), end_min - start_min, 1, color='green'))
        level_dict = {}
        # 设置画布
        for data1 in org_info:
            secLevel = data1['secLevel']
            time_str = data1['eventTime']
            # 将 datetime 对象转换为时间戳
            timestamp = time_str
            # 在10:10位置添加宽度为1分钟的红色部分
            red_start = (timestamp - start_time).total_seconds() / 60
            red_width = 1  # 红色部分宽度，单位是分钟
            ax.add_patch(patches.Rectangle((red_start, 0), red_width, 1, color=color_dict[int(secLevel)]))
        # 配置x轴
        plt.xlim([start_min, end_min])
        plt.xticks([i * 60 for i in range(25)], [f'{i:02d}:00' for i in range(25)])
        plt.xlabel('Time')

        # 移除y轴和顶部、右侧边框
        ax.yaxis.set_visible(False)
        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.spines['left'].set_visible(False)
        save_name = str(day) + ".png"
        # plt.show()
        plt.savefig(os.path.join(save_path, save_name), dpi=300, bbox_inches='tight',
                    transparent=False)
        plt.close()


# path1 = r'D:\GJ\项目\事故检测\output0220 - 副本\algorithm\V6.0'
# path2 = r'D:\GJ\项目\事故检测\output0220 - 副本\filee'
# path3 = r'D:\GJ\项目\事故检测\output0220\file'
# # main(path1, path2)
# for root, dirs, files in os.walk(path1):
#     for file in files:
#         if file.endswith('.json'):
#             floder_name = file.split('.')[0]
#             path_json = os.path.join(path1, file)
#             path_source_png = os.path.join(path3, floder_name)
#             path_png = os.path.join(path2, floder_name)
#             if os.path.exists(path_png):
#                 shutil.rmtree(path_png)
#                 # 复制文件夹
#             shutil.copytree(path_source_png, path_png)
#             print(path_png)
#             main(path_json, path_png)


def main1(true_json_path, event_json_path, save_path, version, truth_flag=False):
    all_result = {
        "true_result": {},
        "event_result": {},
        "yongdu_result": {}
    }
    color_dict = {1: "cyan", 2: "yellow", 3: "red"}

    with open(true_json_path, 'r', encoding='utf-8') as file:
        for line in file:
            try:
                data = json.loads(line)
                ID = data["id"]
                all_result["true_result"][ID] = {"true": [], "detection": [], "congestion": []}
                for i in data["truthValue"]:
                    event_time = datetime.strptime(i["eventTime"].split(' ')[1], '%H:%M:%S')
                    all_result["true_result"][ID]["true"].append({"eventTime": event_time, "duration": 20, "secLevel": 3})
                for j in data["detectionValue"]:
                    start_time = datetime.strptime(j["startTime"].split(' ')[1], '%H:%M:%S')
                    end_time = datetime.strptime(j["endTime"].split(' ')[1], '%H:%M:%S')
                    duration = int((end_time - start_time).total_seconds() / 60)
                    all_result["true_result"][ID]["detection"].append({"eventTime": start_time, "duration": duration,
                                                                       "secLevel": 2})
                for k in data["congestionValue"]:
                    start_time = datetime.strptime(k["startTime"].split(' ')[1], '%H:%M:%S')
                    end_time = datetime.strptime(k["endTime"].split(' ')[1], '%H:%M:%S')
                    duration = int((end_time - start_time).total_seconds() / 60)
                    all_result["true_result"][ID]["congestion"].append({"eventTime": start_time, "duration": duration,
                                                                        "secLevel": 1})
            except json.JSONDecodeError:
                print(f"解析true_json_path文件行 {line} 时出错。")

    with open(event_json_path, 'r', encoding='utf-8') as file:
        for line in file:
            try:
                data = json.loads(line)
                ID = data["id"]
                all_result["event_result"][ID] = []
                all_result["yongdu_result"][ID] = []
                for j in data["algorithmValue"]:
                    if j["eventType"] == "阻断":
                        start_time = datetime.strptime(j["startTime"].split(' ')[1][:5], '%H:%M')
                        end_time = datetime.strptime(j["endTime"].split(' ')[1][:5], '%H:%M')
                        duration = int((end_time - start_time).total_seconds() / 60)
                        all_result["event_result"][ID].append({"eventTime": start_time, "duration": duration,
                                                               "secLevel": int(j["level"])})
                    else:
                        start_time = datetime.strptime(j["startTime"].split(' ')[1][:5], '%H:%M')
                        end_time = datetime.strptime(j["endTime"].split(' ')[1][:5], '%H:%M')
                        duration = int((end_time - start_time).total_seconds() / 60)
                        all_result["yongdu_result"][ID].append({"eventTime": start_time, "duration": duration,
                                                               "secLevel": int(j["level"])})
            except json.JSONDecodeError:
                print(f"解析event_json_path文件行 {line} 时出错。")

    # 计算时间点位置
    start_time = datetime.strptime("00:00:00", "%H:%M:%S")
    end_time = datetime.strptime("23:59:59", "%H:%M:%S")
    # 将时间转换为相对于起始时间的分钟数，用于定位
    start_min = 0
    end_min = (end_time - start_time).total_seconds() / 60

    folder_names = get_non_recursive_folders(save_path)
    source_path = os.path.dirname(save_path)

    for source, source_data in all_result.items():
        if source == "true_result" and truth_flag:
            for ID, org_info in source_data.items():
                if ID in folder_names:
                    fig, ax = plt.subplots(figsize=(20, 1))
                    ax.add_patch(patches.Rectangle((start_min, 0), end_min - start_min, 1, color='green'))
                    for data1 in org_info["detection"]:
                        level = data1['secLevel']
                        timestamp = data1['eventTime']
                        duration = data1['duration']
                        red_start = (timestamp - start_time).total_seconds() / 60
                        ax.add_patch(patches.Rectangle((red_start, 0), duration, 1, color=color_dict[level]))
                    for data2 in org_info["true"]:
                        level = data2['secLevel']
                        timestamp = data2['eventTime']
                        duration = data2['duration']
                        red_start = (timestamp - start_time).total_seconds() / 60
                        ax.add_patch(patches.Rectangle((red_start, 0), duration, 1, color=color_dict[level]))
                    for data3 in org_info["congestion"]:
                        level = data3['secLevel']
                        timestamp = data3['eventTime']
                        duration = data3['duration']
                        red_start = (timestamp - start_time).total_seconds() / 60
                        ax.add_patch(patches.Rectangle((red_start, 0), duration, 0.5, color=color_dict[level]))
                    # 配置x轴
                    plt.xlim([start_min, end_min])
                    plt.xticks([i * 60 for i in range(25)], [f'{i:02d}:00' for i in range(25)])
                    # 移除y轴和顶部、右侧边框
                    ax.yaxis.set_visible(False)
                    ax.spines['top'].set_visible(False)
                    ax.spines['right'].set_visible(False)
                    ax.spines['left'].set_visible(False)
                    plt.savefig(os.path.join(save_path, ID, "true_result.png"), dpi=200, bbox_inches='tight',
                                transparent=False)
                    plt.close()
                else:
                    print(f"save_path目录下的{ID}文件夹不存在")

        if source == "event_result":
            for ID, org_info in source_data.items():
                if ID in folder_names:
                    fig, ax = plt.subplots(figsize=(20, 1))
                    ax.add_patch(patches.Rectangle((start_min, 0), end_min - start_min, 1, color='green'))
                    for data1 in org_info:
                        level = data1['secLevel']
                        timestamp = data1['eventTime']
                        duration = data1['duration']
                        red_start = (timestamp - start_time).total_seconds() / 60
                        ax.add_patch(patches.Rectangle((red_start, 0), duration, 1, color=color_dict[level]))
                    # 配置x轴
                    plt.xlim([start_min, end_min])
                    plt.xticks([i * 60 for i in range(25)], [f'{i:02d}:00' for i in range(25)])
                    # 移除y轴和顶部、右侧边框
                    ax.yaxis.set_visible(False)
                    ax.spines['top'].set_visible(False)
                    ax.spines['right'].set_visible(False)
                    ax.spines['left'].set_visible(False)
                    save_png_path = os.path.join(source_path, "algorithm", version, "block")
                    if not os.path.exists(save_png_path):
                        os.makedirs(save_png_path)
                    save_png_file = os.path.join(save_png_path, str(ID) + ".png")
                    plt.savefig(save_png_file, dpi=200, bbox_inches='tight', transparent=False)
                    plt.close()
                else:
                    print(f"save_path目录下的{ID}文件夹不存在")

        if source == "yongdu_result":
            for ID, org_info in source_data.items():
                if ID in folder_names:
                    fig, ax = plt.subplots(figsize=(20, 1))
                    ax.add_patch(patches.Rectangle((start_min, 0), end_min - start_min, 1, color='green'))
                    for data1 in org_info:
                        level = data1['secLevel']
                        timestamp = data1['eventTime']
                        duration = data1['duration']
                        red_start = (timestamp - start_time).total_seconds() / 60
                        ax.add_patch(patches.Rectangle((red_start, 0), duration, 1, color=color_dict[level]))
                    # 配置x轴
                    plt.xlim([start_min, end_min])
                    plt.xticks([i * 60 for i in range(25)], [f'{i:02d}:00' for i in range(25)])
                    # 移除y轴和顶部、右侧边框
                    ax.yaxis.set_visible(False)
                    ax.spines['top'].set_visible(False)
                    ax.spines['right'].set_visible(False)
                    ax.spines['left'].set_visible(False)
                    save_png_path = os.path.join(source_path, "algorithm", version, "congestion")
                    if not os.path.exists(save_png_path):
                        os.makedirs(save_png_path)
                    save_png_file = os.path.join(save_png_path, str(ID) + ".png")
                    plt.savefig(save_png_file, dpi=200, bbox_inches='tight', transparent=False)
                    plt.close()
                else:
                    print(f"save_path目录下的{ID}文件夹不存在")


# path1 = r'D:\GJ\项目\事故检测\output0220 - 副本\algorithm\V6.0'
# path2 = r'D:\GJ\项目\事故检测\output0220 - 副本\filee'
# path3 = r'D:\GJ\项目\事故检测\output0220\file'


# 真值json文件，存放真值数据
true_json_path = r"D:\GJ\项目\事故检测\output0311\output19\truth.json"
# 事件json文件，存放事件数据，用于生成事件时间条
event_json_path = r"D:\GJ\项目\事故检测\output0305_3\algorithm\V2.6\readme.json"
# 真值特征图保存路径，并存放真值时间条
save_path = r"D:\GJ\项目\事故检测\output0311\output19\file"

# main1(true_json_path, event_json_path, save_path, "V2.1", truth_flag=True)


# ID_list = []
# with open(event_json_path, 'r', encoding='utf-8') as f:
#     for line in f:
#         data = json.loads(line)
#         ID_list.append(data["id"])
# print(len(ID_list))
# floder_list = []
# try:
#     for entry in os.scandir(save_path):
#         # 只处理目录且非递归，即只考虑当前目录下一层
#         # if entry.is_dir() and entry.name not in ID_list:
#         if entry.is_dir():
#             floder_list.append(entry.name)
#             # 删除该文件夹
#             # shutil.rmtree(entry.path)
#             # print(f"已删除文件夹: {entry.path}")
# except FileNotFoundError:
#     print(f"指定的目录 {save_path} 未找到。")
# except PermissionError:
#     print(f"没有足够的权限删除文件夹，请检查目录权限。")
#
# result1 = []
# for item in ID_list:
#     if item not in floder_list:
#         result1.append(item)
# result2 = []
# for item in floder_list:
#     if item not in ID_list:
#         result2.append(item)
# print(result1)
# print(result2)

# for root, dirs, files in os.walk(path1):
#     for file in files:
#         if file.endswith('.json'):
#             floder_name = file.split('.')[0]
#             path_json = os.path.join(path1, file)
#             path_source_png = os.path.join(path3, floder_name)
#             path_png = os.path.join(path2, floder_name)
#             if os.path.exists(path_png):
#                 shutil.rmtree(path_png)
#
#             shutil.copytree(path_source_png, path_png)
#             print(path_png)
#             main1(true_json_path, event_json_path, save_path)




# json1 = r'D:\GJ\项目\事故检测\output0228_2\algorithm\V1.0\readme.json'
# json2 = r'D:\GJ\项目\事故检测\output0305_2\algorithm\V1.0\readme1.json'
# json3 = r'D:\GJ\项目\事故检测\output0305_3\algorithm\V1.0\readme1.json'
# data = []
# with open(json1, 'r', encoding='utf-8') as f:
#     for line in f:
#         data.append(json.loads(line))
# with open(json2, 'r', encoding='utf-8') as f:
#     for line in f:
#         data.append(json.loads(line))
# with open(json3, 'w', encoding='utf-8') as f:
#     for item in data:
#         f.write(json.dumps(item, ensure_ascii=False) + '\n')

# 计算时间点位置
start_time = datetime.strptime("00:00:00", "%H:%M:%S")
end_time = datetime.strptime("23:59:59", "%H:%M:%S")
# 将时间转换为相对于起始时间的分钟数，用于定位
start_min = 0
end_min = (end_time - start_time).total_seconds() / 60
fig, ax = plt.subplots(figsize=(20, 1))
ax.add_patch(patches.Rectangle((start_min, 0), end_min - start_min, 1, color='green'))
color_dict = {1: "cyan", 2: "yellow", 3: "red"}
start_timeq = datetime.strptime("2024-09-30 12:06:00".split(' ')[1], '%H:%M:%S')
end_timeq = datetime.strptime("2024-05-24 23:00:00".split(' ')[1], '%H:%M:%S')
duration = int((end_timeq - start_timeq).total_seconds() / 60)
reaa = datetime.strptime("2024-02-05 13:22:00".split(' ')[1], '%H:%M:%S')
timestamp = start_timeq
red_start = (timestamp - start_time).total_seconds() / 60
# ax.add_patch(patches.Rectangle((red_start, 0), duration, 1, color=color_dict[2]))
# ax.add_patch(patches.Rectangle((red_start, 0), duration, 0.5, color=color_dict[1]))
ax.add_patch(patches.Rectangle((red_start, 0), 20, 1, color=color_dict[3]))
# 配置x轴
plt.xlim([start_min, end_min])
plt.xticks([i * 60 for i in range(25)], [f'{i:02d}:00' for i in range(25)])
# 移除y轴和顶部、右侧边框
ax.yaxis.set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
save_png_path = os.path.join(r"D:\GJ\项目\事故检测\output0311\output19", "algorithm", "V2.1")
if not os.path.exists(save_png_path):
    os.makedirs(save_png_path)
save_png_file = os.path.join(save_png_path, str(112) + ".png")
plt.savefig(save_png_file, dpi=200, bbox_inches='tight', transparent=False)
plt.close()
